/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb.common;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.ejb.Singleton;

/**
 *
 * @author Carmela
 */
@Singleton
public class TripleDES implements TripleDESLocal {

    private static final String digestKey = "HG58YZ3CR9";
    private static byte[] keyBytes;

    @Override
    public String encrypt(String text) throws Exception {
        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "SunJCE");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);

        final byte[] plainTextBytes = text.getBytes("utf-8");
        final byte[] cipherText = cipher.doFinal(plainTextBytes);

        return Base64.encode(cipherText);
    }

    @Override
    public String decrypt(String textEncrypt) throws Exception {
        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "SunJCE");
        decipher.init(Cipher.DECRYPT_MODE, key, iv);

        final byte[] encData = Base64.decode(textEncrypt);

        final byte[] plainText = decipher.doFinal(encData);

        return new String(plainText, "UTF-8");
    }

    public TripleDES() {
        try {
            final MessageDigest md = MessageDigest.getInstance("md5");
            final byte[] digestOfPassword = md.digest(digestKey.getBytes("utf-8"));
            keyBytes = Arrays.copyOf(digestOfPassword, 24);
            for (int j = 0, k = 16; j < 8;) {
                keyBytes[k++] = keyBytes[j++];
            }
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(TripleDES.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(TripleDES.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
